---
import { i18n } from '../../i18n/translation';
import I18nKey from '../../i18n/i18nKey';
import Icon from '../misc/Icon.astro';

export interface Props {
  item: {
    id: string;
    title: string;
    description: string;
    type: 'education' | 'work' | 'project' | 'achievement';
    startDate: string;
    endDate?: string;
    location?: string;
    organization?: string;
    position?: string;
    skills?: string[];
    achievements?: string[];
    links?: {
      name: string;
      url: string;
      type: 'website' | 'certificate' | 'project' | 'other';
    }[];
    icon?: string;
    color?: string;
    featured?: boolean;
  };
  showTimeline?: boolean;
  size?: 'small' | 'medium' | 'large';
  layout?: 'card' | 'timeline';
}

const { 
  item, 
  showTimeline = true, 
  size = 'medium',
  layout = 'timeline'
} = Astro.props;

// 类型图标映射
const getTypeIcon = (type: string) => {
  switch (type) {
    case 'education': return 'material-symbols:school';
    case 'work': return 'material-symbols:work';
    case 'project': return 'material-symbols:code';
    case 'achievement': return 'material-symbols:emoji-events';
    default: return 'material-symbols:event';
  }
};

// 类型颜色映射
const getTypeColor = (type: string) => {
  switch (type) {
    case 'education': return 'bg-blue-100 text-blue-700 dark:bg-blue-900/30 dark:text-blue-400';
    case 'work': return 'bg-green-100 text-green-700 dark:bg-green-900/30 dark:text-green-400';
    case 'project': return 'bg-purple-100 text-purple-700 dark:bg-purple-900/30 dark:text-purple-400';
    case 'achievement': return 'bg-orange-100 text-orange-700 dark:bg-orange-900/30 dark:text-orange-400';
    default: return 'bg-gray-100 text-gray-700 dark:bg-gray-900/30 dark:text-gray-400';
  }
};

// 类型文本映射
const getTypeText = (type: string) => {
  switch (type) {
    case 'education': return i18n(I18nKey.timelineEducation);
    case 'work': return i18n(I18nKey.timelineWork);
    case 'project': return i18n(I18nKey.timelineProject);
    case 'achievement': return i18n(I18nKey.timelineAchievement);
    default: return type;
  }
};

// 链接图标映射
const getLinkIcon = (type: string) => {
  switch (type) {
    case 'certificate': return '🏆';
    case 'project': return '🔗';
    case 'website': return '🌐';
    default: return '📄';
  }
};

// 格式化日期
const formatDate = (dateString: string) => {
  const date = new Date(dateString);
  return date.toLocaleDateString('zh-CN', { year: 'numeric', month: 'long' });
};

// 计算持续时间
const getDuration = (startDate: string, endDate?: string) => {
  const start = new Date(startDate);
  const end = endDate ? new Date(endDate) : new Date();
  const diffTime = Math.abs(end.getTime() - start.getTime());
  const diffMonths = Math.ceil(diffTime / (1000 * 60 * 60 * 24 * 30));
  
  if (diffMonths < 12) {
    return `${diffMonths} ${i18n(I18nKey.timelineMonths)}`;
  } else {
    const years = Math.floor(diffMonths / 12);
    const months = diffMonths % 12;
    if (months === 0) {
      return `${years} ${i18n(I18nKey.timelineYears)}`;
    } else {
      return `${years} ${i18n(I18nKey.timelineYears)} ${months} ${i18n(I18nKey.timelineMonths)}`;
    }
  }
};

// 尺寸样式映射
const getSizeClasses = (size: string) => {
  switch (size) {
    case 'small':
      return {
        container: 'p-4',
        node: 'w-8 h-8',
        nodeIcon: 'text-lg',
        title: 'text-lg',
        meta: 'text-xs',
        description: 'text-sm',
        badge: 'text-xs'
      };
    case 'large':
      return {
        container: 'p-8',
        node: 'w-16 h-16',
        nodeIcon: 'text-2xl',
        title: 'text-2xl',
        meta: 'text-base',
        description: 'text-base',
        badge: 'text-sm'
      };
    default: // medium
      return {
        container: 'p-6',
        node: 'w-12 h-12',
        nodeIcon: 'text-xl',
        title: 'text-xl',
        meta: 'text-sm',
        description: 'text-sm',
        badge: 'text-xs'
      };
  }
};

const sizeClasses = getSizeClasses(size);
const itemColor = item.color || '#3B82F6';
---

{layout === 'timeline' ? (
  <!-- 时间线布局 -->
  <div class="relative flex items-start gap-6">
    <!-- 时间线节点 -->
    {showTimeline && (
      <div class={`relative z-10 rounded-full flex items-center justify-center shrink-0 ${sizeClasses.node}`} style={`background-color: ${itemColor}`}>
        <Icon 
          icon={item.icon || getTypeIcon(item.type)} 
          class={`text-white ${sizeClasses.nodeIcon}`}
          color="white"
          fallback={item.title.charAt(0)}
          loading="eager"
        />
      </div>
    )}
    
    <!-- 内容卡片 -->
    <div class="flex-1 bg-white dark:bg-gray-800 rounded-lg border border-black/10 dark:border-white/10 hover:shadow-lg transition-shadow duration-300">
      <div class={sizeClasses.container}>
        <!-- 标题和类型 -->
        <div class="flex items-start justify-between mb-3">
          <div>
            <h3 class={`font-semibold text-black/90 dark:text-white/90 mb-1 ${sizeClasses.title}`}>
              {item.title}
              {item.featured && (
                <span class="ml-2 text-yellow-500">⭐</span>
              )}
            </h3>
            {item.organization && (
              <div class={`text-black/70 dark:text-white/70 ${sizeClasses.meta}`}>
                {item.organization} {item.position && `• ${item.position}`}
              </div>
            )}
          </div>
          <span class={`px-2 py-1 rounded-full shrink-0 ml-4 ${sizeClasses.badge} ${getTypeColor(item.type)}`}>
            {getTypeText(item.type)}
          </span>
        </div>
        
        <!-- 时间和地点信息 -->
        <div class={`flex items-center gap-4 mb-3 text-black/60 dark:text-white/60 ${sizeClasses.meta}`}>
          <div>
            {formatDate(item.startDate)} - {item.endDate ? formatDate(item.endDate) : i18n(I18nKey.timelinePresent)}
          </div>
          <div>•</div>
          <div>{getDuration(item.startDate, item.endDate)}</div>
          {item.location && (
            <>
              <div>•</div>
              <div>📍 {item.location}</div>
            </>
          )}
        </div>
        
        <!-- 描述 -->
        <p class={`text-black/70 dark:text-white/70 mb-4 ${sizeClasses.description}`}>
          {item.description}
        </p>
        
        <!-- 成就 -->
        {item.achievements && item.achievements.length > 0 && (
          <div class="mb-4">
            <h4 class={`font-semibold text-black/80 dark:text-white/80 mb-2 ${sizeClasses.meta}`}>
              {i18n(I18nKey.timelineAchievements)}
            </h4>
            <ul class="space-y-1">
              {item.achievements.map((achievement) => (
                <li class={`text-black/70 dark:text-white/70 flex items-start gap-2 ${sizeClasses.description}`}>
                  <span class="text-green-500 mt-1">•</span>
                  <span>{achievement}</span>
                </li>
              ))}
            </ul>
          </div>
        )}
        
        <!-- 技能 -->
        {item.skills && item.skills.length > 0 && (
          <div class="mb-4">
            <div class="flex flex-wrap gap-1">
              {item.skills.map((skill) => (
                <span class={`px-2 py-1 bg-gray-100 text-gray-700 dark:bg-gray-700 dark:text-gray-300 rounded ${sizeClasses.badge}`}>
                  {skill}
                </span>
              ))}
            </div>
          </div>
        )}
        
        <!-- 链接 -->
        {item.links && item.links.length > 0 && (
          <div class="flex gap-4">
            {item.links.map((link) => (
              <a 
                href={link.url} 
                target="_blank" 
                rel="noopener noreferrer"
                class={`text-blue-600 dark:text-blue-400 hover:underline font-medium flex items-center gap-1 transition-colors ${sizeClasses.meta}`}
              >
                {getLinkIcon(link.type)}
                {link.name}
              </a>
            ))}
          </div>
        )}
      </div>
    </div>
  </div>
) : (
  <!-- 卡片布局 -->
  <div class="bg-white dark:bg-gray-800 rounded-lg border border-black/10 dark:border-white/10 hover:shadow-lg transition-shadow duration-300">
    <div class={sizeClasses.container}>
      <!-- 图标和标题 -->
      <div class="flex items-start gap-4 mb-3">
        <div class={`rounded-lg flex items-center justify-center shrink-0 ${sizeClasses.node}`} style={`background-color: ${itemColor}20`}>
          <iconify-icon icon={item.icon || getTypeIcon(item.type)} class={sizeClasses.nodeIcon} style={`color: ${itemColor}`}></iconify-icon>
        </div>
        <div class="flex-1">
          <div class="flex items-start justify-between mb-2">
            <h3 class={`font-semibold text-black/90 dark:text-white/90 ${sizeClasses.title}`}>
              {item.title}
              {item.featured && (
                <span class="ml-2 text-yellow-500">⭐</span>
              )}
            </h3>
            <span class={`px-2 py-1 rounded-full shrink-0 ml-2 ${sizeClasses.badge} ${getTypeColor(item.type)}`}>
              {getTypeText(item.type)}
            </span>
          </div>
          {item.organization && (
            <div class={`text-black/70 dark:text-white/70 mb-1 ${sizeClasses.meta}`}>
              {item.organization} {item.position && `• ${item.position}`}
            </div>
          )}
          {item.location && (
            <div class={`text-black/60 dark:text-white/60 mb-2 ${sizeClasses.meta}`}>
              📍 {item.location}
            </div>
          )}
        </div>
      </div>
      
      <!-- 时间信息 -->
      <div class={`text-black/70 dark:text-white/70 mb-3 ${sizeClasses.meta}`}>
        {formatDate(item.startDate)} - {item.endDate ? formatDate(item.endDate) : i18n(I18nKey.timelinePresent)} ({getDuration(item.startDate, item.endDate)})
      </div>
      
      <!-- 描述 -->
      <p class={`text-black/60 dark:text-white/60 mb-4 ${sizeClasses.description}`}>
        {item.description}
      </p>
      
      <!-- 成就 -->
      {item.achievements && item.achievements.length > 0 && (
        <div class="mb-4">
          <h4 class={`font-semibold text-black/80 dark:text-white/80 mb-2 ${sizeClasses.meta}`}>
            {i18n(I18nKey.timelineAchievements)}
          </h4>
          <ul class="space-y-1">
            {item.achievements.slice(0, 3).map((achievement) => (
              <li class={`text-black/70 dark:text-white/70 flex items-start gap-2 ${sizeClasses.description}`}>
                <span class="text-green-500 mt-1">•</span>
                <span>{achievement}</span>
              </li>
            ))}
            {item.achievements.length > 3 && (
              <li class={`text-black/60 dark:text-white/60 ${sizeClasses.description}`}>
                ... 还有 {item.achievements.length - 3} 项成就
              </li>
            )}
          </ul>
        </div>
      )}
      
      <!-- 技能和链接 -->
      <div class="flex items-center justify-between">
        {item.skills && item.skills.length > 0 && (
          <div class="flex flex-wrap gap-1">
            {item.skills.slice(0, 3).map((skill) => (
              <span class={`px-2 py-1 bg-gray-100 text-gray-700 dark:bg-gray-700 dark:text-gray-300 rounded ${sizeClasses.badge}`}>
                {skill}
              </span>
            ))}
            {item.skills.length > 3 && (
              <span class={`px-2 py-1 bg-gray-100 text-gray-700 dark:bg-gray-900/30 dark:text-gray-400 rounded ${sizeClasses.badge}`}>
                +{item.skills.length - 3}
              </span>
            )}
          </div>
        )}
        
        {item.links && item.links.length > 0 && (
          <div class="flex gap-3">
            {item.links.slice(0, 2).map((link) => (
              <a 
                href={link.url} 
                target="_blank" 
                rel="noopener noreferrer"
                class={`text-blue-600 dark:text-blue-400 hover:underline font-medium transition-colors ${sizeClasses.meta}`}
              >
                {getLinkIcon(link.type)} {link.name}
              </a>
            ))}
          </div>
        )}
      </div>
    </div>
  </div>
)}

<script>
  // 加载 Iconify 图标库
  if (typeof window !== 'undefined' && !window.iconifyLoaded) {
    const script = document.createElement('script');
    script.src = 'https://code.iconify.design/iconify-icon/1.0.7/iconify-icon.min.js';
    document.head.appendChild(script);
    window.iconifyLoaded = true;
  }
</script>